﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using ICSharpCode.NRefactory;

namespace Commander.Core.Refactorings.Modifiers {

	public class NetLongMessageChainModifier : NetWalkerCodeModifier {
		private int m_lineOfDefect;
		private string m_source;
		private string m_path;

		public NetLongMessageChainModifier(XElement extra, IParser parser)
			: base(extra, parser) {
				m_source = extra.Attribute("src").Value;
				m_path = extra.Attribute("path").Value;
				m_lineOfDefect = GetLineNo(m_source);
		}

		public NetLongMessageChainModifier() {

		}

		int GetLineNo(string source) {
			int startPos = source.IndexOf("≈");
			int endPos = source.IndexOf(")", startPos);
			string lineNoString = source.Substring(startPos + 1, endPos - startPos - 1);
			return Convert.ToInt32(lineNoString);
		}

		public int DefectLine {
			get {
				return this.m_lineOfDefect;
			}
		}

		public override string ApplyModification() {
			string line;
			int i = 1;

			string fileContent = null;

			if (File.Exists(m_path)) {
				StreamReader file = null;
				try {
					file = new StreamReader(m_path);
					while ((line = file.ReadLine()) != null) {
						if (i++ == DefectLine) {
							int firstEqual = line.IndexOf('=');
							int ln = firstEqual + 1;
							string unchanged = line.Substring(0, firstEqual + 1);
							string x = "testVar";
							int var = 0;
							int startIndex = firstEqual + 1;
							bool firstVar = false;
							string removeLongChain = null;
							while (line[ln] != ';') {
								int splitposition = line.IndexOf(")", startIndex);
								string substr = line.Substring(startIndex, splitposition - startIndex + 1);
								if (!firstVar) {
									removeLongChain = removeLongChain + "\t var " + x + "" + var + " = " + substr + ";\n";
									firstVar = true;
								}
								else {
									removeLongChain = removeLongChain + "\t var " + x + "" + var + " = " + x + (var - 1) + substr + ";\n";
								}
								var++;
								startIndex = splitposition + 1;
								ln = startIndex;
							}
							removeLongChain = removeLongChain + unchanged + x + (var - 1) + ";\n";
							fileContent = fileContent + removeLongChain + "\n";
						}
						else {
							fileContent = fileContent + line + "\n";
						}
					}
				}
				finally {
					if (file != null)
						file.Close();
				}
			}
			return fileContent;
		}
	}
}
